import sys
import logging
import time
from loguru import logger as loger,_handler
import pymysql
import traceback
from conf.settings import *
from logging import getLogger, INFO


class DatabaseLogHandler(logging.Handler):
    def __init__(self):
        self.db = pymysql.connect(
            host=DBConfig['userdb']['HOST'],
            port=DBConfig['userdb']['PORT'],
            user=DBConfig['userdb']['USER'],
            passwd=DBConfig['userdb']['PASSWORD'],
            db=DBConfig['userdb']['DATABASE'])
        self.table = 'user_log'
        self.cursor = self.db.cursor()
        self.db.commit()
        logging.Handler.__init__(self)

    def emit(self, record):
        # trace = None
        # if sys.exc_info()[2]:
        #     trace = traceback.format_exc()
        # kwargs = {
        #     'logger_name': record.name,
        #     'level': record.levelname,
        #     'level_no': record.levelno,
        #     'msg': record.getMessage(),
        #     'trace': trace,
        #     'file_name': record.filename,
        #     'func_name': record.funcName,
        #     'path_name': record.pathname,
        #     'line_no': record.lineno
        # }
        kwargs = f'{record.getMessage()}'
        # kwargs = f"{time.strftime('%Y-%m-%d %H:%M:%S')} | {record.levelname} | {record.getMessage()}"
        sql_insert = f"INSERT INTO {self.table}(`info`) VALUES (%s)"
        # print(tuple(kwargs.values()))
        try:
            self.cursor.execute(sql_insert, str(kwargs))
            self.db.commit()
        except:
            traceback.print_exc()

def get_logger():
    handler = DatabaseLogHandler()
    loger.add(handler)
    # logger.info('haha')
    return loger

# def get_logger():
#     logger_sql = getLogger()
#     logger_sql.setLevel(INFO)
#     dblog = DatabaseLogHandler()
#     logger_sql.addHandler(dblog)
#     return logger_sql


# if __name__ == '__main__':
#     logger = get_logger()
#     logger.info('日志的msg内容')
#     try:
#         1 / 0
#     except Exception as e:
#         # logger.error(e)
#         pass